package com.example;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordHashingExample {
    public static void main(String[] args) {
        String salt = "U9i%=N+m]#i9yvUV:bA/3n4X9JdPXf=n";
        String password = "secret";

        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");

            // 使用平台默认编码
            Charset defaultCharset = Charset.defaultCharset();

            // 尝试多种处理方式
            testHashing(digest, salt, password, defaultCharset);
            testHashing(digest, salt.trim(), password.trim(), defaultCharset);
            testHashing(digest, salt.toUpperCase(), password.toUpperCase(), defaultCharset);
            testHashing(digest, salt.toLowerCase(), password.toLowerCase(), defaultCharset);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    private static void testHashing(MessageDigest digest, String salt, String password, Charset charset) {
        byte[] saltBytes = salt.getBytes(charset);
        byte[] passwordBytes = password.getBytes(charset);

        // 先拼接盐值再拼接密码
        byte[] combined1 = new byte[saltBytes.length + passwordBytes.length];
        System.arraycopy(saltBytes, 0, combined1, 0, saltBytes.length);
        System.arraycopy(passwordBytes, 0, combined1, saltBytes.length, passwordBytes.length);

        // 先拼接密码再拼接盐值
        byte[] combined2 = new byte[passwordBytes.length + saltBytes.length];
        System.arraycopy(passwordBytes, 0, combined2, 0, passwordBytes.length);
        System.arraycopy(saltBytes, 0, combined2, passwordBytes.length, saltBytes.length);

        byte[] hashBytes1 = digest.digest(combined1);
        byte[] hashBytes2 = digest.digest(combined2);

        StringBuilder hexString1 = new StringBuilder(2 * hashBytes1.length);
        for (byte b : hashBytes1) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString1.append('0');
            }
            hexString1.append(hex);
        }

        StringBuilder hexString2 = new StringBuilder(2 * hashBytes2.length);
        for (byte b : hashBytes2) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString2.append('0');
            }
            hexString2.append(hex);
        }

        System.out.println("盐值: " + salt + ", 密码: " + password + ", 编码: " + charset.name());
        System.out.println("先拼接盐值再拼接密码的 SHA - 256 哈希值: " + hexString1.toString());
        System.out.println("先拼接密码再拼接盐值的 SHA - 256 哈希值: " + hexString2.toString());
        System.out.println("------------------------");
    }
}